package com.example.ai.inventory.service;

import com.example.ai.inventory.entity.PurchaseOrder;
import com.example.ai.inventory.entity.PurchaseItem;
import com.example.ai.inventory.repository.PurchaseOrderRepository;
import com.example.ai.inventory.repository.PurchaseItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;

/**
 * 采购服务实现类
 */
@Service
public class PurchaseServiceImpl implements PurchaseService {
    
    @Autowired
    private PurchaseOrderRepository purchaseOrderRepository;
    
    @Autowired
    private PurchaseItemRepository purchaseItemRepository;
    
    @Autowired
    private ProductService productService;
    
    private final Random random = new Random();
    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
    
    @Override
    @Transactional
    public PurchaseOrder createPurchaseOrder(PurchaseOrder order) {
        // 生成采购单号
        String orderNo = generateOrderNo();
        order.setOrderNo(orderNo);
        
        // 计算采购总金额
        calculateTotalAmount(order);
        
        // 保存采购单
        PurchaseOrder savedOrder = purchaseOrderRepository.save(order);
        
        // 保存采购明细并更新商品库存
        if (order.getItems() != null && !order.getItems().isEmpty()) {
            for (PurchaseItem item : order.getItems()) {
                item.setOrderId(savedOrder.getId());
                purchaseItemRepository.save(item);
                
                // 更新商品库存（采购入库）
                productService.updateProductStock(item.getProductId(), item.getQuantity());
            }
        }
        
        return savedOrder;
    }
    
    @Override
    public PurchaseOrder getPurchaseOrderById(Long id) {
        PurchaseOrder order = purchaseOrderRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("采购单不存在：" + id));
        
        // 加载采购明细
        loadPurchaseItems(order);
        
        return order;
    }
    
    @Override
    public PurchaseOrder getPurchaseOrderByOrderNo(String orderNo) {
        PurchaseOrder order = purchaseOrderRepository.findByOrderNo(orderNo)
                .orElseThrow(() -> new RuntimeException("采购单不存在：" + orderNo));
        
        // 加载采购明细
        loadPurchaseItems(order);
        
        return order;
    }
    
    @Override
    public List<PurchaseOrder> getPurchaseOrders(LocalDateTime startTime, LocalDateTime endTime) {
        List<PurchaseOrder> orders;
        if (startTime != null && endTime != null) {
            orders = purchaseOrderRepository.findByCreateTimeBetween(startTime, endTime);
        } else {
            orders = purchaseOrderRepository.findAll();
        }
        
        // 加载每个订单的明细
        for (PurchaseOrder order : orders) {
            loadPurchaseItems(order);
        }
        
        return orders;
    }
    
    @Override
    public List<PurchaseItem> getPurchaseItemsByOrderId(Long orderId) {
        return purchaseItemRepository.findByOrderId(orderId);
    }
    
    @Override
    public List<PurchaseItem> getPurchaseHistoryByProductId(Long productId) {
        return purchaseItemRepository.findByProductId(productId);
    }
    
    /**
     * 生成采购单号
     */
    private String generateOrderNo() {
        String dateStr = LocalDateTime.now().format(formatter);
        int randomNum = 10000 + random.nextInt(90000); // 生成5位随机数
        return "PO" + dateStr + randomNum;
    }
    
    /**
     * 计算采购总金额
     */
    private void calculateTotalAmount(PurchaseOrder order) {
        if (order.getItems() != null && !order.getItems().isEmpty()) {
            double totalAmount = order.getItems().stream()
                    .mapToDouble(item -> item.getQuantity() * item.getUnitPrice())
                    .sum();
            order.setTotalAmount(totalAmount);
        }
    }
    
    /**
     * 加载采购明细
     */
    private void loadPurchaseItems(PurchaseOrder order) {
        List<PurchaseItem> items = purchaseItemRepository.findByOrderId(order.getId());
        order.setItems(items);
    }
}